const { Client } = require("ssh2");
var inquirer = require("inquirer");
const sshServer = require("./ssh");
const { runCommand } = require("./handleCommand");
const { releaseDir, deployDir, ssh } = require("./config");
const ora = require('ora');
const chalk = require("chalk");
const log = console.log;
// 恢复版本
async function main() {
  try {
    const spinner = ora(`获取远程目录-${deployDir}`).start();
    let options = [
      {
        type: "list",
        message: "请选择你要恢复的版本：",
        name: "version",
        default: "",
        choices: ["取消恢复"],
      },
    ];
    // 获取远程目录
    const list = await getRemoteDir();
    // 过滤目录
    filterList(options, list);
    spinner.stop()
    // 获取用户选择的版本
    const res = await result(options);
    // 是否取消恢复
    if (res.version == "取消恢复") {
      log(chalk.yellow("已取消恢复"));
      process.exit();
    }
    // 连接
    const SSH = await sshServer(ssh);
    // 删除 发布目录
    await runCommand(SSH, "rm -rf " + releaseDir, deployDir);
    // 把备份目录改成发布目录
    await runCommand(SSH, `mv ${res.version} ${releaseDir}`, deployDir);
    log(chalk.green(`✨ 恢复版本成功--${res.version}`));
  } catch (err) {
    log(chalk.red(`恢复版本失败:${err}`));
  } finally {
    process.exit();
  }
}
main();

function getRemoteDir() {
  return new Promise((resolve, reject) => {
    const conn = new Client();
    conn
      .on("ready", () => {
        // console.log("Client :: ready");
        conn.sftp((err, sftp) => {
          if (err) reject(err);
          sftp.readdir(deployDir, (err, list) => {
            if (err) reject(err);
            resolve(list);
            conn.end();
          });
        });
      })
      .connect(ssh);
  });
}

function filterList(options, list) {
  list.forEach((item) => {
    if (item.filename.indexOf(":") > -1) {
      options[0].choices.unshift(item.filename);
    }
  });
}

function result(options) {
  return new Promise((resolve, reject) => {
    inquirer
      .prompt(options)
      .then((answers) => {
        resolve(answers);
      })
      .catch((error) => {
        reject(error);
        // if (error.isTtyError) {
        //   // Prompt couldn't be rendered in the current environment
        // } else {
        //   // Something else went wrong
        // }
      });
  });
}
